package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.tables.CustomerDebtTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.CustomerTypeTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.ui.works.adapters.PcustomerDebtAdapter;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户收欠款页面
 */
public class CustomerDebtActivity extends Activity {

    @ViewInject(R.id.pcustomerDebt_txtTitle) private TextView txtTitle;//页面标题
    @ViewInject(R.id.pcustomerDebt_txtIcon) private TextView txtIcon;//客户头像
    @ViewInject(R.id.pcustomerDebt_txtCustomerName)private TextView txtCustomerName;//客户名称
    @ViewInject(R.id.pcustomerDebt_txtCustomerAddress)private TextView txtCustomerAddress;//客户地址
    @ViewInject(R.id.pcustomerDebt_txtContactor)private TextView txtContactor;//联系人信息
    @ViewInject(R.id.pcustomerDebt_txtContacts)private TextView txtDelieverGoodsInfo;//收货人信息
    @ViewInject(R.id.pcustomerDebt_txtDistace)private TextView txtDistance;//距离信息
    @ViewInject(R.id.pcustomerDebt_lstDebt)private ListView lstDebt;//收欠款列表
    @ViewInject(R.id.pcustomerDebt_txtCounter)private TextView txtCounter;//数量计数器
    @ViewInject(R.id.pcustomerDebt_txtMoneyCounter)private TextView txtMoneyCounter;//金额计数器

    private int netCustomerId = 0,//客户网络ID
                netAddressId = 0;//客户网络收货地址ID
    private int selectedCount = 0;//选中的数量
    private double selectedMoney = 0;//选中的金额数
    private ArrayList<CustomerDebtTable> lstCustomerDebtInfo = null;//客户欠款数据列表
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_debt);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        Intent intent = getIntent();
        if(intent!=null){
            netCustomerId = intent.getIntExtra("netCustomerId",0);
            netAddressId = intent.getIntExtra("netAddressId",0);
        }
        initActivity();//初始化页面操作
        findAllDebtInfo();//查找欠款订单列表
    }

    /**
     * 初始化页面
     */
    public void initActivity(){
        new AsyncTask<Void,Void,Void>(){
            private CustomerTable ct = null;
            private CustomerTypeTable ctt = null;
            private DeliverGoodsTable dt = null;
            private ProgressDialog dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(CustomerDebtActivity.this,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    ct = dbUtils.findFirst(Selector.from(CustomerTable.class).where("id","=",netCustomerId));
                    dt = dbUtils.findFirst(Selector.from(DeliverGoodsTable.class).where("id","=",netAddressId));
                    if(dt!=null) ctt = dbUtils.findFirst(Selector.from(CustomerTypeTable.class).where("id","=",dt.khlx));
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null) dialog.dismiss();
                if(ct!=null && dt!=null && ctt!=null){
                    txtIcon.setText(ctt.dttb);
                    txtTitle.setText(ct.mc+"-收欠款");
                    txtCustomerName.setText(ct.mc);
                    txtCustomerAddress.setText("地址："+dt.shdz);
                    txtContactor.setText(ct.lxr+" "+ct.dh);
                    txtDelieverGoodsInfo.setText(dt.shr+" "+dt.shdh);
                    if(SystemData.currentLocation!=null && !TextUtils.isEmpty(dt.jwd.toString())){//计算距离信息
                        String[] latlngs = dt.jwd.split(",");
                        txtDistance.setText(FormatUtils.exactDistance(new LatLng(SystemData.currentLocation.getLatitude(),
                                SystemData.currentLocation.getLongitude()),new LatLng(Double.parseDouble(latlngs[0]),
                                Double.parseDouble(latlngs[1]))));
                    }
                }else{
                    Toast.makeText(CustomerDebtActivity.this, "页面初始化失败!", Toast.LENGTH_SHORT).show();
                    CustomerDebtActivity.this.finish();
                }
            }
        }.execute();
    }

    @OnClick(value = {R.id.pcustomerDebt_txtDebt})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pcustomerDebt_txtDebt://收欠款
                if(selectedCount <= 0 || selectedMoney<=0.00000){
                    Toast.makeText(this,"本次支付金额为0!",Toast.LENGTH_SHORT).show();
                    return;
                }
//                if(!checkDebtInformation()){
//                    Toast.makeText(this,"请检查是否有超额支付!",Toast.LENGTH_SHORT).show();
//                    return;
//                }
                Intent intent = new Intent(this,DebtStatisticsActivity.class);
                intent.putExtra("netCustomerId",netCustomerId);
                intent.putExtra("netAddressId",netAddressId);
                intent.putExtra("debtMoney",selectedMoney);
                intent.putParcelableArrayListExtra("listDebt",lstCustomerDebtInfo);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
            default:
                break;
        }
    }

//    /**
//     * 检测欠款支付参数
//     */
//    public boolean checkDebtInformation(){
//        PcustomerDebtAdapter adapter = (PcustomerDebtAdapter)lstDebt.getAdapter();
//        if(adapter == null) return false;
//        List<CustomerDebtTable> lst = adapter.getDataSource();
//        for(int i=0;i<lst.size();i++){
//            final CustomerDebtTable item = lst.get(i);
//            if(Float.compare(item.wsje,item.payableMoney)<0){
//                return false;
//            }
//        }
//        return true;
//    }

    /**
     * 查看所有的欠款信息
     */
    public void findAllDebtInfo(){
        new AsyncTask<Void,Void,Void>(){
            private String errorMessage = null;
            private List<CustomerDebtTable> customerDebtTableList = null;
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    customerDebtTableList = dbUtils.findAll(Selector.from(CustomerDebtTable.class)
                            .where("kh_id","=",netCustomerId).and("shdz_id","=",netAddressId));
                }catch(Exception  e){
                    e.printStackTrace();
                    errorMessage = "查询欠款列表失败!原因："+e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(errorMessage!=null){
                    Toast.makeText(CustomerDebtActivity.this,errorMessage,Toast.LENGTH_SHORT).show();
                    return;
                }
                lstDebt.setAdapter(new PcustomerDebtAdapter(CustomerDebtActivity.this,
                        customerDebtTableList,new PcustomerDebtAdapter.OnCheckValueChangedListener() {
                    @Override
                    public void onCheckValueChanged(HashMap<Integer,Boolean> selector,int checkedNum, int totalNum, double payableMoney, double totalMoney) {
                        selectedCount = checkedNum;
                        selectedMoney = payableMoney;
                        txtCounter.setText(checkedNum+"/"+totalNum);
                        txtMoneyCounter.setText(FormatUtils.exactNumber(payableMoney,"0.00")
                                +"/"+FormatUtils.exactNumber(totalMoney,"0.00")+"元");
                        if(checkedNum>0) {//有选中的数量,并添加至选中数据集合中，传递给下一个页面
                            if(lstCustomerDebtInfo == null)
                                lstCustomerDebtInfo = new ArrayList<CustomerDebtTable>();
                            lstCustomerDebtInfo.clear();
                            for (Map.Entry<Integer, Boolean> item : selector.entrySet()) {
                                lstCustomerDebtInfo.add(customerDebtTableList.get(item.getKey()));
                            }
                        }
                    }
                }));
            }
        }.execute();
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pcustomerDebt_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
